<?php 
namespace App\Console\Commands;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Link;
use EasyWeChat\Message\News;
use Illuminate\Console\Command;
use Log;
use DB;
use App\WxPublicUser;
use App\WxMessage;
use App\WxMsglog;

class CrontabMsg extends Command {

    protected $config = [
        'app_id' => 'wx555be570d21859aa',
        'secret' => '85cf4af9ee65c80e18cf29a1580a5e51',
        'token' => 'leyougame2018'
    ];

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'cron:msg';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $app = new Application($this->config);
        $now = time() - (48 * 3600);
        $ago_time = date('Y-m-d H:i:s', $now);
        $users = WxPublicUser::where('updated_at', '>', $ago_time)->where(['status' => 1])->get();//48小时内的活跃用户
        if ($users) {
            foreach ($users as $user) {
                $info = $app->user->get($user->openid);
                if ($info->subscribe != 1) {//已经不再关注公众号的用户
                    continue;
                }
                $time_begin = date('H.i', time() - 1800);
                $time_end = date('H.i', time() + 1800);
                $infos = WxMessage::where(['status' => 1, 'type' => 2])->whereBetween('crontab', [$time_begin, $time_end])->get();//获取公众平台定时推送信息
                if ($infos) {
                    foreach ($infos as $info) {
                        $log = WxMsglog::where(['user_id' => $user->id, 'msg_id' => $info->id])->whereBetween('created_at', [date("Y-m-d"), date("Y-m-d",strtotime("+1 day"))])->first();
                        if (!$log) {//已经发送的不再发送
                            try {
                                $wxinfo = base64_decode($info->content);
                                /*发送信息*/
                                $text = new Text(['content' => $wxinfo]);
                                $openId = $user->openid;
                                $staff = $app->staff;
                                $staff->message($text)->to($openId)->send();
                                $wxlog = new WxMsglog;
                                $wxlog->user_id = $user->id;
                                $wxlog->msg_id = $info->id;
                                $wxlog->type = $info->type;
                                $wxlog->save();
                            } catch (\EasyWeChat\Core\Exception $e) {
                                continue;
                            }
                        }
                    }
                }
            }
        }
    }
}